package connmobroute

import (
	"errors"
	"git.sr.ht/~mil/mobroute/src/apiroute"
	utodorename "git.sr.ht/~mil/mobroute/src/utilfuncs"
	"git.sr.ht/~mil/transito/utilfuncs"
	"time"
)

func MobrouteExecuteRoute(r MobrouteRequest) (*MobrouteResponse, error) {
	if mapParams, err := mobrouteRequestToRouteParams(r); err != nil {
		return nil, err
	} else {
		return apiroute.CommandRoute(mapParams)
	}
}

func mobrouteRequestToRouteParams(r MobrouteRequest) (*apiroute.RouteParams, error) {
	if sources, err := utilfuncs.ParseCsvToInts(r.Sources); err != nil {
		return nil, err
	} else if len(r.LatLonFrom) < 2 || len(r.LatLonTo) < 2 {
		return nil, errors.New("Latlon from/to invalid")
	} else {
		return &apiroute.RouteParams{
			CacheDir:           ptr("/data/data/ht.sr.git.transito/databases/"),
			Filter:             &apiroute.SourcesetFilter{Mdbid: sources},
			From:               &utodorename.Coord{Lat: r.LatLonFrom[0], Lon: r.LatLonFrom[1]},
			To:                 &utodorename.Coord{Lat: r.LatLonTo[0], Lon: r.LatLonTo[1]},
			Time:               ptr(time.Now()),
			MaxTripSeconds:     ptr(parseUint(r.MaxTripMinutes) * 60),
			MinTransferSeconds: ptr(parseUint(r.MinTransferMinutes) * 60),
			MaxTransferSeconds: ptr(parseUint(r.MaxTransferMinutes) * 60),
			MaxWalkSeconds:     ptr(parseUint(r.MaxWalkMinutes) * 60),
			WalkspeedKmHr:      ptr(parseFloat64(r.WalkspeedKmHr)),
			TransfersTable:     ptr(r.TransfersTable),
			TransfersGenerated: ptr(r.TransfersGenerated),
		}, nil
	}
}
